package com.mo.controller;

import com.mo.common.Result;
import com.mo.entity.params.LoginParam;
import com.mo.entity.User;
import com.mo.entity.vo.LoginVo;
import com.mo.entity.vo.UserInfoVo;
import com.mo.enums.ResultCode;
import com.mo.security.entity.LoginUser;
import com.mo.service.UserService;
import com.mo.utils.JwtUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Objects;

@RestController
public class LoginController {
    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private UserService userService;
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private PasswordEncoder passwordEncoder;

    @PostMapping("login")
    public Result login(@RequestBody LoginParam loginParam) {
        // 在这里获取 UserDetailsService 中 loadUserByUsername 返回的用户信息
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginParam.getUsername(), loginParam.getPassword());
        Authentication authenticated = authenticationManager.authenticate(authenticationToken);
        LoginUser loginUser = (LoginUser) authenticated.getPrincipal();

        if (Objects.isNull(loginUser)) {
            return Result.error("用户名或密码有误", HttpServletResponse.SC_BAD_REQUEST);
        }

        // 把userId放到token里面
        String userId = loginUser.getUser().getUserId().toString();
        String username = loginUser.getUser().getUsername();
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        claims.put("username", username);
        String token = jwtUtils.generateToken(userId, claims);
        Date expirationDate = jwtUtils.getExpirationDate(token);
        LoginVo loginVo = new LoginVo(token, Integer.valueOf(userId), expirationDate.getTime());

        return Result.success(loginVo);
    }

    @GetMapping("user-info")
    public Result userInfo(@RequestParam Integer userId) {
        User user = userService.getById(userId);
        if (Objects.isNull(user)) {
            return Result.error(ResultCode.USER_NOT_EXIST);
        }
        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setName(user.getUsername());
        userInfoVo.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        return Result.success(userInfoVo);
    }

    @PostMapping("user-logout")
    public Result logout() {
        return Result.success();
    }
}
